from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Count, Sum, Q
from django.contrib.auth import get_user_model

from .models import Product, Category, ProductImage, Order, OrderItem, Address, UserProfile
from .forms import ProductForm, CategoryForm, OrderStatusForm, UserForm, AddressForm, ProductImageForm, OrderForm

User = get_user_model()



class HomeListView(LoginRequiredMixin, ListView):
    model = Product
    paginate_by = 3
    page_kwarg = 'pn'
    template_name = 'main/index.html'
    login_url = '/login/'

class CreateProjectView(LoginRequiredMixin, CreateView):
    model = Product
    form_class = ProductForm
    template_name = 'main/create.html'
    success_url = '/main/home/'
    login_url = '/login/'

class HomeUpdateView(LoginRequiredMixin, UpdateView):
    model = Product
    form_class = ProductForm
    template_name = 'main/update.html'
    success_url = '/main/home/'
    login_url = '/login/'

class HomeDeleteView(LoginRequiredMixin, DeleteView):
    model = Product
    template_name = 'main/delete.html'
    success_url = '/main/home/'
    login_url = '/login/'

class CategoryListView(LoginRequiredMixin, ListView):
    model = Category
    template_name = 'main/category.html'
    context_object_name = 'category'
    login_url = '/login/'

class CategoryCreateView(LoginRequiredMixin, CreateView):
    model = Category
    form_class = CategoryForm
    template_name = 'main/category_create.html'
    success_url = reverse_lazy('main:category')
    login_url = '/login/'

class CategoryDeleteView(LoginRequiredMixin, DeleteView):
    model = Category
    template_name = 'main/category_delete.html'
    success_url = reverse_lazy('main:category')
    login_url = '/login/'
    
    def get_object(self, queryset=None):
        pk = self.kwargs.get('pk')
        return get_object_or_404(Category, pk=pk)

class CategoryDetailView(LoginRequiredMixin, ListView):
    model = Product
    template_name = 'main/index.html'
    paginate_by = 3
    page_kwarg = 'pn'
    context_object_name = 'product_list'
    login_url = '/login/'
    
    def get_queryset(self):
        category_id = self.kwargs.get('pk')
        return Product.objects.filter(category=category_id)
        
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        category_id = self.kwargs.get('pk')
        try:
            category = Category.objects.get(id=category_id)
            context['current_category'] = category
        except Category.DoesNotExist:
            context['current_category'] = None
        return context


class ProductImageListView(LoginRequiredMixin, ListView):
    """商品图片列表视图"""
    model = ProductImage
    template_name = 'main/product_image_list.html'
    context_object_name = 'image_list'
    paginate_by = 12
    page_kwarg = 'pn'
    login_url = '/login/'
    
    def get_queryset(self):
        return ProductImage.objects.select_related('product').order_by('-created_at')


class ProductDetailView(LoginRequiredMixin, DetailView):
    """商品详情视图"""
    model = Product
    template_name = 'main/product_detail.html'
    context_object_name = 'product'
    login_url = '/login/'


class ProductImageCarouselView(LoginRequiredMixin, DetailView):
    """商品图片轮播视图"""
    model = Product
    template_name = 'main/product_image_carousel.html'
    context_object_name = 'product'
    login_url = '/login/'


# 订单管理视图
class OrderListView(LoginRequiredMixin, ListView):
    """订单列表视图"""
    model = Order
    template_name = 'main/order_list.html'
    context_object_name = 'orders'
    paginate_by = 10
    
    def get_queryset(self):
        queryset = Order.objects.select_related('user', 'shipping_address').prefetch_related('items__product')
        status = self.request.GET.get('status')
        if status:
            queryset = queryset.filter(status=status)
        return queryset.order_by('-created_at')
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['status_choices'] = Order.ORDER_STATUS
        context['current_status'] = self.request.GET.get('status', '')
        return context


class OrderDetailView(LoginRequiredMixin, DetailView):
    """订单详情视图"""
    model = Order
    template_name = 'main/order_detail.html'
    context_object_name = 'order'


class OrderUpdateView(LoginRequiredMixin, UpdateView):
    """订单状态更新视图"""
    model = Order
    form_class = OrderStatusForm
    template_name = 'main/order_update.html'
    success_url = reverse_lazy('main:order_list')


# 用户管理视图
class UserListView(LoginRequiredMixin, ListView):
    """用户列表视图"""
    model = User
    template_name = 'main/user_list.html'
    context_object_name = 'users'
    paginate_by = 20
    
    def get_queryset(self):
        return User.objects.select_related('profile').annotate(
            order_count=Count('orders')
        ).order_by('-date_joined')


class UserDetailView(LoginRequiredMixin, DetailView):
    """用户详情视图"""
    model = User
    template_name = 'main/user_detail.html'
    context_object_name = 'user_detail'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user = self.get_object()
        context['orders'] = user.orders.all()[:10]
        context['addresses'] = user.addresses.all()
        return context


# 地址管理视图
class AddressListView(LoginRequiredMixin, ListView):
    """地址列表视图"""
    model = Address
    template_name = 'main/address_list.html'
    context_object_name = 'addresses'
    paginate_by = 20
    
    def get_queryset(self):
        return Address.objects.select_related('user').order_by('-created_at')


# 用户增删改视图
class UserCreateView(LoginRequiredMixin, CreateView):
    model = User
    form_class = UserForm
    template_name = 'main/user_form.html'
    success_url = reverse_lazy('main:user_list')

class UserUpdateView(LoginRequiredMixin, UpdateView):
    model = User
    form_class = UserForm
    template_name = 'main/user_form.html'
    success_url = reverse_lazy('main:user_list')

class UserDeleteView(LoginRequiredMixin, DeleteView):
    model = User
    template_name = 'main/user_confirm_delete.html'
    success_url = reverse_lazy('main:user_list')

# 地址增删改视图
class AddressCreateView(LoginRequiredMixin, CreateView):
    model = Address
    form_class = AddressForm
    template_name = 'main/address_form.html'
    success_url = reverse_lazy('main:address_list')

class AddressUpdateView(LoginRequiredMixin, UpdateView):
    model = Address
    form_class = AddressForm
    template_name = 'main/address_form.html'
    success_url = reverse_lazy('main:address_list')

class AddressDeleteView(LoginRequiredMixin, DeleteView):
    model = Address
    template_name = 'main/address_confirm_delete.html'
    success_url = reverse_lazy('main:address_list')

# 商品图片增删改视图
class ProductImageCreateView(LoginRequiredMixin, CreateView):
    model = ProductImage
    form_class = ProductImageForm
    template_name = 'main/product_image_form.html'
    success_url = reverse_lazy('main:product_images')

class ProductImageUpdateView(LoginRequiredMixin, UpdateView):
    model = ProductImage
    form_class = ProductImageForm
    template_name = 'main/product_image_form.html'
    success_url = reverse_lazy('main:product_images')

class ProductImageDeleteView(LoginRequiredMixin, DeleteView):
    model = ProductImage
    template_name = 'main/product_image_confirm_delete.html'
    success_url = reverse_lazy('main:product_images')

# 订单增删改视图
class OrderCreateView(LoginRequiredMixin, CreateView):
    model = Order
    form_class = OrderForm
    template_name = 'main/order_form.html'
    success_url = reverse_lazy('main:order_list')

class OrderDeleteView(LoginRequiredMixin, DeleteView):
    model = Order
    template_name = 'main/order_confirm_delete.html'
    success_url = reverse_lazy('main:order_list')

# 统计视图
class DashboardView(LoginRequiredMixin, ListView):
    """管理仪表板"""
    model = Product
    template_name = 'main/dashboard.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        # 基础统计
        context['total_products'] = Product.objects.count()
        context['total_users'] = User.objects.count()
        context['total_orders'] = Order.objects.count()
        context['total_categories'] = Category.objects.count()
        
        # 订单状态统计
        context['order_stats'] = Order.objects.values('status').annotate(
            count=Count('id')
        ).order_by('status')
        
        # 低库存商品
        context['low_stock_products'] = Product.objects.filter(
            stock__lte=10
        ).order_by('stock')[:10]
        
        # 最新订单
        context['recent_orders'] = Order.objects.select_related(
            'user', 'shipping_address'
        ).order_by('-created_at')[:10]
        
        return context
